package Thread.wait_notiofy;

/**
 * 线程的等待方法
 */
public class WaitDemo1 {
    private static class WaitTesk implements Runnable{
        private Object lock;
        public WaitTesk(Object lock){
            this.lock=lock;
        }
        @Override
        public void run() {
            synchronized (lock){
                System.out.println(Thread.currentThread().getName()+"准备进入等待状态~~");
                //此线程在等到lock对象的notify方法唤醒
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName()+"等待结束，线程机组执行~~");
            }
          }
    }
    private static class NotifyTask implements Runnable{
        private Object lock;
        public NotifyTask(Object lock){
            this.lock=lock;
        }
        @Override
        public void run() {
           synchronized (lock){
               System.out.println(Thread.currentThread().getName()+"准备唤醒~~");
               //随机唤醒一个处在lock对象上等待的线程
               lock.notify();
               System.out.println(Thread.currentThread().getName()+"唤醒成功~~");
           }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Object lock=new Object();
        //创建3个等待线程
        Thread t1=new Thread(new WaitTesk(lock),"t1");
        Thread t2=new Thread(new WaitTesk(lock),"t2");
        Thread t3=new Thread(new WaitTesk(lock),"t3");
        //创建一个唤醒线程
        Thread notify=new Thread(new NotifyTask(lock),"notify线程");
        t1.start();
        t2.start();
        t3.start();
        Thread.sleep(1000);
        notify.start();
    }
}

